package org.ielts.action.security;

import static com.yifeng.struts2.ResultConstants.FILL;

import org.ielts.action.BaseAction;
import org.ielts.domain.security.Role;
import org.ielts.domain.security.User;
import org.ielts.service.security.RoleService;
import org.ielts.service.security.UserRoleService;
import org.ielts.service.security.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import com.yifeng.modules.annotations.Module;
import com.yifeng.modules.annotations.Operation;
import com.yifeng.struts2.action.FormAction;
import com.yifeng.utils.JsonResultBuilder;
import com.yifeng.utils.PageUtils;
import com.yifeng.web.Pagers;
import com.yifeng.web.Paginations;

import static com.yifeng.struts2.RequestParameters.*;
import static com.yifeng.struts2.ResultParameters.*;
import static com.yifeng.struts2.ResultConstants.*;
import static com.yifeng.struts2.ActionUtils.*;

@Module(namespaceName = "security")
public class UserRoleAction extends BaseAction {

	@Autowired
	UserRoleService userRoleService;

	@Operation(result = FILL)
	public String listUserInRole() {
		String roleId = form.readString("id");
		String userName = form.readString("userName");

		Pageable pageable = getPageable();

		Page<User> users = userRoleService.listUserInRole(roleId, userName, pageable);
		put("users", users);
		Role role = roleService.findRole(roleId);
		put("role", role);

		put(PAGINATIONS, new Paginations(users));

		return FILL;
	}

	@Autowired
	UserService userService;
	@Autowired
	RoleService roleService;

	@Operation(result = JSON)
	public String doAddUserInRole() {
		String roleId = form.readString("roleId");
		String[] userIds = form.readStrings("userId");

		userRoleService.addUserInRole(userIds, roleId);

		setJson(JsonResultBuilder.success(true).msg("添加新用户到角色中成功。").json());

		return JSON;
	}

	@Operation(result = JSON)
	public String doRemoveUserFromRole() {
		String roleId = form.readString("roleId");
		String[] userIds = form.readStrings("userId");

		userRoleService.removeUserFromRole(userIds, roleId);

		setJson(JsonResultBuilder.success(true).msg("从角色中移除用户成功。").json());

		return JSON;
	}
}
